package org.hard.netty.c2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 王林博
 * @date: 2022年08月13日 9:14
 */
@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        // 使用Nio理解阻塞模式
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //1.创建服务器
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        // 2.绑定监听端口
        socketChannel.bind(new InetSocketAddress(8080));


        // 3.accept
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            // accept 建立与客户端的连接  SocketChannel 与客户端之间通信
            log.info("connecting....");
            SocketChannel accept = socketChannel.accept();  // 阻塞方法，线程停止运行,等到连接
            log.info("connectted....:{}", accept);
            channels.add(accept);
            // 5.接收客户端发送的数据
            for (SocketChannel channel : channels) {
                log.info("before read....:{}", channel);
                channel.read(buffer);       // 阻塞方法
                buffer.flip();  // 读模式
                // 打印
                System.out.println(buffer.toString());
                buffer.clear(); // 写模式
                log.info("after read....:{}", channel);
            }

        }
    }
}
